<template>
    <div class="centre font f16">
        <div class="bg-fff bor pl-10 pt-10 pr-10 pb-5">
            <div class="flex jc-sb">
                <div>
                    <el-button plain @click="add">New</el-button>
                    <el-button plain @click="save">Save</el-button>
                    <el-button v-if="powerList.inquiry&&powerList.inquiry.inquiry_add_to_order" type="primary" @click="open()" plain>Add to Order</el-button>
                    <el-button v-if="powerList.inquiry&&powerList.inquiry.inquiry_add_to_quotation" type="primary" @click="AddToQuotation" plain class="addQuotation">Add to
                        Quotation</el-button>
                    <el-popconfirm title="Sure to delete?" @confirm="del">
                        <template #reference>
                            <el-button type="primary" plain class="del">Delete</el-button>
                        </template>
                    </el-popconfirm>
                </div>
                <div class="flex jc-e">
                    <el-select v-model="leading" :disabled="store.type != 2" @change="unifiedLeading" class="w60p"
                        placeholder="LEADING">
                        <el-option v-for="item in newLeading" :key="item.label" :label="item.label" :value="item.label" />
                    </el-select>
                </div>
            </div>
            <p class="fwb f70 mt-5">RFQ DETAIL {{ rfqId }} of {{ centerTable.length - 1 }} Quoted</p>
            <!-- 表格 -->
            <div class="boxTable  pb-5 bg-fff pl-10 brs">
                <div class="table">
                    <p class="flex aic pl-10 pb-5 f14 tabTitle" style="border-bottom: 1px solid #EBEEF5; color:#909399">
                        <el-checkbox v-model="tabCheckAll" :indeterminate="tabIsIndeterminate"
                            @change="tabHandleCheckAllChange"><br></el-checkbox>
                        <span class="ml-5" style="width: 13.5%;">MODEL</span>
                        <span style="width: 13.5%;">BRAND</span>
                        <span style="width: 6%;">QTY</span>
                        <span class="w15p">MultipleBuyer</span>
                        <span v-if="powerList.inquiry&&powerList.inquiry.inquiry_price.Isdisplay" class="w8p">PRICE</span>
                        <!-- <span :class="{ 'w12p': store.type != 3, 'w16p': store.type == 3 }">LEADING</span> -->
                        <span :class="powerList.inquiry&&powerList.inquiry.inquiry_price.Isdisplay?'w12p':'w16p'">LEADING</span>
                        <span :class="powerList.inquiry&&powerList.inquiry.inquiry_price.Isdisplay?'w12p':'w16p'">CONDITION</span>
                        <span style="width: 8.6%;">BUYER</span>
                        <span class="operation">OPERATION</span>
                    </p>
                    <el-checkbox-group v-loading="loading" v-model="tabCheckedCities" @change="rightSelection">
                        <div v-for="table, index in centerTable" :key="index" @click="clickTable(table)"
                            class="flex bbm jc-c pt-10 pl-10 hoverActive"
                            :class="{ 'active': index == centerTable.findIndex(item => item.product_id == product_id) }">
                            <div class="flex w50p">
                                <el-checkbox :label="table"><br></el-checkbox>
                                <el-select class="ml-5" v-model="table.product.product_id"
                                    :disabled="table.item.quotation_price != '' || !powerList.inquiry.inquiry_model.Isenable" @change="chModel"
                                    :remote-method="getModel" remote @visible-change="visible" filterable
                                    placeholder="MODEL">
                                    <el-option v-for="item in newModel" :key="item.id" :label="item.label"
                                        :value="item.id" />
                                </el-select>
                                <el-select v-model="table.brand.brand_id" class=""
                                    :disabled="table.item.quotation_price != '' || !powerList.inquiry.inquiry_brand.Isenable"
                                    :remote-method="getBrand" remote @visible-change="visible" filterable
                                    placeholder="BRAND">
                                    <el-option v-for="item in newBrand" :key="item.id" :label="item.label"
                                        :value="item.id" />
                                </el-select>
                                <div class=" w15p">
                                    <el-input v-model="table.Qty"
                                        :disabled="table.item.quotation_price != '' || !powerList.inquiry.inquiry_qty.Isenable" placeholder="QTY" />
                                </div>
                                <div class="">
                                    <el-select v-model="table.purchaser_id_list"
                                        :disabled="!powerList.inquiry.inquiry_multiplebuyer.Isenable"
                                        @change="changeBuyer($event, table.purchaser_id_simple_list)" collapse-tags
                                        collapse-tags-tooltip placeholder="BUYER" multiple>
                                        <el-option v-for="item in newBuyer" :key="item.label" :label="item.label"
                                            :value="item.id" />
                                    </el-select>
                                </div>
                            </div>
                            <div class="flex fdc w50p">
                                <div v-for="list in table.item_purchaser_array" class="flex  pb-10">
                                    <div v-show="powerList.inquiry.inquiry_price.Isdisplay" class="w20p">
                                        <el-input v-model="list.quotation_price" :disabled="!powerList.inquiry.inquiry_price.Isenable" placeholder="PRICE"/>
                                    </div>
                                    <el-select class="w30p" v-model="list.leadingtime"
                                        :disabled="!powerList.inquiry.inquiry_leading.Isenable" filterable placeholder="LEADING">
                                        <el-option v-for="item in newLeading" :key="item.label" :label="item.label"
                                            :value="item.case" />
                                    </el-select>
                                    <el-select class="w30p" v-model="list.product_condition"
                                        :disabled="!powerList.inquiry.inquiry_condition.Isenable" filterable
                                        placeholder="CONDITION">
                                        <el-option v-for="item in newCondition" :key="item.label" :label="item.label"
                                            :value="item.case" />
                                    </el-select>
                                    <div class="buyer w20p">
                                        <el-input v-model="list.name" disabled placeholder="BUYER" />
                                    </div>
                                    <!-- <div class="w25p"> </div> -->
                                    <div class="tabDel"
                                        :class="{ 'active': index == centerTable.findIndex(item => item.product_id == product_id) }">
                                        <el-popconfirm title="Sure to delete?" @confirm="tabDel(list)">
                                            <template #reference>
                                                <el-button type="primary" size="small" plain class="del">Delete</el-button>
                                            </template>
                                        </el-popconfirm>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </el-checkbox-group>
                </div>
            </div>
        </div>
        <!-- 图表 -->
        <div ref="main" v-loading="loadingFigure" class="w100p mt-10  pt-5 main" style="height: 30vh"></div>

        <!-- 添加订单弹窗 -->
        <AddOrderVue ref="AddOrder" :newLeading="newLeading" :newCondition="newCondition"></AddOrderVue>

        <!-- 添加到报价弹窗 -->
        <AddQuotationVue ref="AddQuotation" @quote="quote" :newLeading="newLeading" :newCondition="newCondition">
        </AddQuotationVue>
    </div>
</template>

<script setup>
import { ref, watch, onMounted } from "vue";
import AddOrderVue from "./components/AddOrder.vue";
import AddQuotationVue from "./components/AddQuotation.vue";
import { ElMessage } from 'element-plus'
import * as $axios from '../../../api/index'
import useBrand from '../../../hooks/useBrand'
import useModel from '../../../hooks/useModel'
import * as echarts from "echarts";
import custom from '../../../assets/custom.json'
import { useDemoStore } from '../../../pinia/index'
import usePower from "../../../hooks/usePower";
const store = useDemoStore()
echarts.registerTheme('custom', custom)
const { powerList } = usePower()

const props = defineProps({
    rfqId: Number
})

onMounted(() => {
    getBuyer() //触发getBuyer事件把采购id变成采购名
    getBrand()
    getModel()
})

// 加载
const loading = ref(true)
const loadingFigure = ref(true)

// 表格数据
const centerTable = ref([])
const product = () => {
    loading.value = true
    loadingFigure.value = true
    // console.log(props)
    const data = {
        token: store.token,
        id: props.rfqId
    }
    $axios.$Product(data).then(res => {
        loading.value = false
        console.log(res)
        res.Status != 0 && figure()
        if (res.Status != 0) return
        centerTable.value = res.data.data
        product_id.value = centerTable.value[0] && centerTable.value[0].product_id  //图表id
        model.value = centerTable.value[0] && centerTable.value[0].product.model  //图表标题
        figure() //触发获取图表数据的事件
        leading.value = ''  //清空指标
        if (!props.rfqId) return
        centerTable.value.push(
            {
                "Qty": '',
                "product": {
                },
                "index": Math.round(Math.random() * (9000 - 100) + 100),
                "purchaser_array": {

                },
                "item_purchaser_array": [
                    {
                        "id": '',
                        "name": "",
                        "inquiry_item_info_id": '',
                        "purchase_price": '',
                        "leadingtime": "",
                        "quotation_price": ""
                    }
                ],
                "purchaser_id_list": [],
                "brand": {
                    "brand_name": "",
                    "filter": "",
                },
                "item": {
                    "leadingtime": "",
                    "quotation_price": '',
                    "purchase_price": ''
                }
            })
    })
}

// 监听属性
watch(props, () => {
    product()
})

// model选项框，最后一行加一条
const chModel = () => {
    const length = centerTable.value[centerTable.value.length - 1].product.product_id
    // 判断最后一个model框有没有值，有就新增一条空的输入框
    if (length) {
        centerTable.value.push({
            "Qty": '',
            "product": {
                "quotation_price": ''
            },
            "index": Math.round(Math.random() * (9000 - 100) + 100),
            "purchaser_array": [{

            }],
            "item_purchaser_array": [
                {
                    "id": '',
                    "name": "",
                    "inquiry_item_info_id": '',
                    "quotation_price": '',
                    "leadingtime": "",
                    "product_condition": ""
                }
            ],
            "brand": {
                "brand_name": "",
                "filter": "",
            },
            "item": {
                "leadingtime": "",
                "quotation_price": '',
            }
        })
    }
}

// 采购多选框取消选择的时候
const changeBuyer = (val, arr) => {
    const list = val.concat(arr).filter((v, i, arrList) => {  //找出被取消的采购
        return arrList.indexOf(v) === arrList.lastIndexOf(v)
    })
    centerTable.value.forEach(item => {
        if (!item.item_purchaser_array.length) return
        list.forEach(arr2 => {
            const index = item.item_purchaser_array.findIndex(i => i.id == arr2)   //找出被取消的采购所在的位置
            if (index == -1) return
            item.item_purchaser_array.splice(index, 1) //删除数组
            if (item.item_purchaser_array.length == 0) { //如果数组长度为0时，添加一个空数组
                item.item_purchaser_array.push({
                    "purchaser_id": '',
                    "quotation_price": "",
                    "profit_rate": '',
                    "purchase_price": '',
                    "leadingtime": "",
                    "product_condition": ""
                })
            }
        })
    })
}

// 全选框
const tabCheckAll = ref(false)
const tabIsIndeterminate = ref(false)
const tabHandleCheckAllChange = (val) => {
    tabCheckedCities.value = val ? centerTable.value : []
    tabIsIndeterminate.value = false
    rightSelection(tabCheckedCities.value)
}

// 多选框
const tabCheckedCities = ref([])
const InquiryOfId = ref([])
const random = ref([])
const rightSelection = (value) => {
    // console.log(value)
    InquiryOfId.value = []
    random.value = []
    tabCheckAll.value = value.length === centerTable.value.length
    tabIsIndeterminate.value = value.length > 0 && value.length < centerTable.value.length

    value.forEach(item => {
        if (item.index) {
            random.value.push(item.index)
        } else {
            item.purchaser_array.forEach(arr => {
                InquiryOfId.value.push(arr.inquiry_item_info_id)
            })
        }
    })
    // console.log(id.value)
}

// 点击表格
const product_id = ref('') //图表数据
const inquiry_item_info_id = ref('')
const model = ref('') //图表标题
const clickTable = (data) => {
    console.log(data)
    product_id.value = data.product_id
    inquiry_item_info_id.value = data.inquiry_item_info_id
    model.value = data.product.model
    figure()
    init()
}


// model
var newModel = ref([])
const getModel = (text) => {
    newModel.value = { newModel } = useModel(text)
}

// brand
var newBrand = ref([])
const getBrand = (text) => {
    newBrand.value = { newBrand } = useBrand(text)
}

//Buyer(获取销售与采购人员列表)
const newBuyer = ref([])
const getBuyer = () => {
    const data = {
        token: store.token,
        keywords: '采购'
    }
    $axios.$userUser_list(data).then(res => {
        newBuyer.value = res.data.map(item => {
            return {
                'label': item.name,
                'id': item.id
            }
        })
    })
}


// Leading
const newLeading = [
    {
        case: "一周有效",
        label: "+1 week"
    },
    {
        case: "三个月有效",
        label: "+3 mouth"
    },
    {
        case: "今天有效",
        label: "+1 day"
    },
    {
        case: "三天有效",
        label: "+3 day"
    },
    {
        case: "五天有效",
        label: "+5 day"
    },
    {
        case: "一个月有效",
        label: "+1 mouth"
    },
    {
        case: "半年有效",
        label: "+6 mouth"
    },
]

// Condition(状态)
const newCondition = [
    {
        case: "QB全新保内",
        label: "New Sealed Under Guarantee"
    },
    {
        case: "QG全新过保",
        label: "New Sealed Beyond Guarantee"
    },
    {
        case: "QK全新开封保内",
        label: "New Unsealed Under Guarantee"
    },
    {
        case: "QKG全新开封过保",
        label: "New Unsealed Beyond Guarantee"
    },
    {
        case: "F翻新",
        label: "Refurbish"
    },
    {
        case: "E二手",
        label: "Used"
    },
    {
        case: "J兼容",
        label: "Substitute"
    },
    {
        case: "G高仿无牌",
        label: "High Copy Blank Brand"
    },
    {
        case: "GD高仿带牌",
        label: "High Copy With Brand"
    },
    {
        case: "S升级",
        label: "Upgrade"
    },
    {
        case: "W无货",
        label: "Discontinued"
    }
]

// 新增
const addis = ref(true)
const add = () => {
    if (addis.value) {
        addis.value = false
        save()
        centerTable.value = []
        for (let i = 0; i <= 5; i++) {
            centerTable.value.push({
                "Qty": '',
                "inquiry_id": '',
                "msg": 1,
                "product": {
                    "quotation_price": ''
                },
                "item_purchaser_array": [
                    {
                        "id": '',
                        "name": "",
                        "inquiry_item_info_id": '',
                        "purchase_price": '',
                        "leadingtime": "",
                        "quotation_price": ""
                    }
                ],
                "purchaser_array": {},
                "purchaser_id_list": [],
                "brand": {
                    "brand_name": "",
                    "filter": "",
                },
                "item": {
                    "leadingtime": "",
                    "quotation_price": '',
                    "purchase_price": ''
                }
            })
        }
    }
    // console.log(centerTable.value)
}

// 需要上传的数据
const dataArr = (arr) => {
    console.log(arr)
    newArr.value = arr.map(item => {
        return {
            "product_id": item.product.product_id,
            "brand_id": item.brand.brand_id,
            "inquiry_id": item.inquiry_id || '',
            "purchaser_id": item.id || '',
            "inquiry_item_info_id": item.inquiry_item_info_id || '',
            'model': item.product.model,
            'brand': item.brand.brand_name,
            'qty': item.Qty || 0,
            'quotation_price': item.quotation_price || '',
            'leadingtime': item.leadingtime || '',
            'product_condition': item.product_condition || '',
            "risk": "稳妥",
            "Effective": "三天有效",
            "Reliability": "牢靠"
        }
    })
}

// save 保存
const newArr = ref([])
const saveState = ref(true)
const save = () => {
    const arr = ref([])
    centerTable.value.forEach((items) => {
        // console.log(items)
        // 判断是否有model有就是要进行提交的
        if (items.product.product_id) {
            if (items.product.product_id && items.brand.brand_id) {
                saveState.value = true
                if (items.purchaser_id_list.length != 0) {
                    items.purchaser_id_list.forEach((name, index) => {
                        arr.value.push({
                            ...items,
                            ...items.item_purchaser_array[index],
                            id: name,
                            inquiry_item_info_id: items.purchaser_array[index] && items.purchaser_array[index].inquiry_item_info_id
                        })
                        // console.log(arr.value)
                        dataArr(arr.value)
                    })
                } else {

                    arr.value.push({
                        ...items,
                    })
                    dataArr(arr.value)
                }
            } else {
                saveState.value = false
            }
        }
    });

    console.log(centerTable.value)
    // console.log(newArr.value[0].inquiry_id)
    if (newArr.value.length != 0 && saveState.value) { //判断数组是否有数据
        leading.value = ''
        const data = {
            "product": newArr.value,
            'token': store.token,
            "customer_id": 5,
            "inquiry_id": centerTable.value[0].msg == 1 ? '' : props.rfqId
        }

        if (centerTable.value[0].msg) { //新建
            $axios.$add(data).then(res => {
                if (res.Status == 0) {
                    emits('save')
                    addis.value = true
                    // product()
                    ElMessage({
                        message: 'Successful preservation',
                        type: 'success',
                    })
                } else {
                    ElMessage({
                        message: 'Save the error',
                        type: 'warning',
                    })
                }
            })
        } else { //更改保存
            // console.log(centerTable.value[0].msg)
            $axios.$add(data).then(res => {
                if (res.Status == 0) {
                    centerTable.value[0].msg == 1 || product()
                    ElMessage({
                        message: 'Successful preservation',
                        type: 'success',
                    })
                } else {
                    ElMessage({
                        message: 'Save the error',
                        type: 'warning',
                    })
                }
            })
        }
    } else if (props.rfqId) {
        // var time2 = new Date()
        // if (time2 - time.value >= 5000) {
        ElMessage({
            message: 'Please choose model brand',
            type: 'warning',
        })
        //     time.value = time2;
        // }
    }
}

// 新增订单转询盘后触发该事件，然后更新页面
const quote = () => {
    emits('save')
}

const emits = defineEmits(['save'])

// 删除
const del = () => {
    if (InquiryOfId.value.length > 0 || random.value.length > 0) {
        if (InquiryOfId.value && InquiryOfId.value.length > 0) {
            const data = {
                token: store.token,
                inquiry_item_info_id: InquiryOfId.value
            }
            // console.log(centerTable.value)
            $axios.$pollingDel(data).then(res => {
                if (res.Status == 0) {
                    InquiryOfId.value.forEach(item => {
                        const index = centerTable.value.findIndex(arr => arr.inquiry_item_info_id == item)
                        index != -1 && centerTable.value.splice(index, 1)
                    })
                    // product()
                    ElMessage({
                        message: 'successfully delete',
                        type: 'success',
                    })
                }
                // console.log(res)
            })
        }
        if (random.value.length > 0) {
            random.value.forEach(item => {
                const index = centerTable.value.findIndex(arr => arr.index == item)
                index != -1 && centerTable.value.splice(index, 1)  //删除数组里面的成员
            })
        }
    } else {
        ElMessage({
            message: 'Please choose',
            type: 'warning',
        })
    }

}

// 单个采购删除
const tabDel = (val) => {
    // console.log(val)
    const data = {
        token: store.token,
        inquiry_item_info_id: val.inquiry_item_info_id
    }
    $axios.$pollingDel(data).then(res => {
        if (res.Status === 0) {
            centerTable.value.forEach(item => {
                if (!item.item_purchaser_array.length) return
                const index = item.item_purchaser_array.findIndex(arr => arr.inquiry_item_info_id == val.inquiry_item_info_id)
                index != -1 && item.item_purchaser_array.splice(index, 1)
                index != -1 && item.purchaser_id_list.splice(index, 1)
                if (item.item_purchaser_array.length == 0) {
                    const index = centerTable.value.findIndex(arr => arr.inquiry_item_info_id == val.inquiry_item_info_id)
                    index != -1 && centerTable.value.splice(index, 1)
                }
            })

            ElMessage({
                message: 'Successful preservation',
                type: 'success',
            })
        }
    })
}

// 批量更改指标
const leading = ref('')
const unifiedLeading = (data) => {
    centerTable.value.forEach(item => {
        if (item.product.model) {
            item.item_purchaser_array.forEach(arr => {
                arr.leadingtime = data
            })
        }
        // console.log(item)
    })
}

// 图表数据
const figureData = ref([])
const figure = () => {
    loadingFigure.value = true
    const data = {
        token: store.token,
        product_id: product_id.value
    }
    $axios.$offer(data).then(res => {
        loadingFigure.value = false
        // console.log(res.data)
        figureData.value = res.data
        init()
    })
}

// 暴露方法
defineExpose({
    product,
})

// 添加订单弹窗
const AddOrder = ref()
const open = () => {
    AddOrder.value.open()
}

// 添加到报价弹窗
const AddQuotation = ref()
const AddToQuotation = () => {
    AddQuotation.value.poseQuotation()
}


const main = ref() // 使用ref创建虚拟DOM引用，使用时用main.value

// 图表数据
var myChart
const init = () => {
    if (myChart != null && myChart != "" && myChart != undefined) {
        myChart.dispose();//销毁
    }
    myChart = echarts.init(main.value, 'custom');

    var option = {
        title: {
            text: model.value
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
                label: {
                    backgroundColor: '#fff'
                }
            }
        },
        legend: {
            data: ['Historical inquiry']
        },
        toolbox: {
            feature: {
                saveAsImage: {}
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: [
            {
                type: 'category',
                boundaryGap: false,
                data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
            }
        ],
        yAxis: [
            {
                type: 'value'
            }
        ],
        series: [
            {
                name: 'Historical inquiry',
                type: 'line',
                stack: 'Total',
                areaStyle: {},
                emphasis: {
                    focus: 'series'
                },
                data: figureData.value
            }
        ]
    };
    option && myChart.setOption(option);
    window.addEventListener("resize", myChart.resize) //自动缩放

}


</script>

<style lang="less">
.el-input__inner {
    font-family: 'swis';
}

// .el-table .cell{
//     padding: 0;
// } </style>
<style lang="less" scoped>
@import '../rfq.less';

.boxTable {
    // position: relative;
    height: 53.8vh;
    overflow: hidden;

    .table {
        width: 60vw;

        .active {
            background-color: #F5F7FA;
        }

        .hoverActive:hover .tabDel {
            background-color: #F5F7FA;
            transition: all 0.1s ease-in;
        }

        .hoverActive:hover {
            background-color: #F5F7FA;
            transition: all 0.1s ease-in;
        }

        .tabTitle {
            // border: 1px solid red;
            position: sticky;
            top: 0;
            z-index: 9;
            background-color: #fff;
        }
    }

    .bbm {
        border-bottom: 1px solid #EBEEF5;
    }

    .operation {
        // border: 1px solid red;
        text-align: center;
        width: 90px;
        right: 0%;
        position: sticky;
        background-color: #fff;
    }

    .tabDel {
        // border: 1px solid red;
        width: 100px;
        padding-left: 15px;
        padding-right: 15px;
        padding-top: 3px;
        position: sticky;
        display: flex;
        justify-content: center;
        right: 0%;
        background-color: #fff;
        z-index: 5;
    }

}

.boxTable:hover {
    overflow: overlay;
    z-index: 3;
}

::-webkit-scrollbar {
    height: 5px;
    width: 5px;
}

::-webkit-scrollbar-track {
    border-radius: 10px;
}

::-webkit-scrollbar-thumb {
    border-radius: 10px;
    background-color: #C8C9CC;
}


.w8p {
    width: 8.2%;
}

.w6p {
    width: 6%;
}

.w7p {
    width: 7.3%;
}

.w9p {
    width: 9%;
}

.w12p {
    width: 12.5%;
}

.w13p {
    width: 13%;
}

.w16p {
    width: 16.2%;
}

.w15p {
    width: 15%;
}</style>